package com.zhupf.dynamic;

/**
 * @author zhupf
 * @date 2024年04月09日 10:46
 * @Description 300. 最长递增子序列
 */
public class LengthOfLIS {

    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];
        int max = 1;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                    max = Math.max(max, dp[i] + 1);
                }
            }
        }
        return max;
    }

    public static void main(String[] args) {
        int[] nums = {3, 5, 6, 2, 5, 4, 19, 5, 6, 7, 12};
        System.out.println(lengthOfLIS2(nums));
    }

    /**
     * 二分查找 + 贪心  利用单调递增
     * @param nums
     * @return
     */
    public static int lengthOfLIS2(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int len = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > dp[len]) {
                dp[++len] = nums[i];
            } else {
                int r = len;
                int l = 0;
                int pos = 0;
                while (l <= r) {
                    int mid = (r + l) / 2;
                    if (nums[i] > dp[mid]) {
                        l = mid + 1;
                    } else {
                        pos = mid;
                        r = mid - 1;
                    }
                }
                dp[pos] = nums[i];
            }
        }
        return len + 1;
    }


}
